package com.smsc.headend.task.engine.handler.impl.deviceconfig;

import cn.hutool.core.map.MapUtil;
import com.smsc.headend.common.enums.Dictionary;
import com.smsc.headend.module.protocol.DeviceData;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskHandlerException;
import com.smsc.headend.task.engine.handler.TaskHandler;
import com.smsc.headend.task.engine.service.CosemXmlService;
import com.smsc.headend.task.engine.service.FeignAssetManagementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * @author wxh
 * @date 2021/1/25
 */
@Slf4j
public class SetDisplayCodeHandler implements TaskHandler {
    @Autowired
    CosemXmlService cosemXmlService;
    @Autowired
    FeignAssetManagementService assetManagementService;
    @Autowired
    TaskDAO taskDAO;

    @Override
    public int handle(Task task, AtomicTask atomicTask, DeviceData deviceData, String actionResult) throws UDISTaskHandlerException {
        log.info("{} action result {}", atomicTask.getAtomicTaskNo(), actionResult);
        Map<String, Object> param = getParameterMap(task, atomicTask);
        Long lpDataItemId = MapUtil.getLong(param, "dataItemId");

        //前台约定key为 captureObj1020070001
        if (task.getIsODR()) {
            String name = String.format("captureObj%s", lpDataItemId);
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), name, "success", 600l, Boolean.TRUE);

            if (isSubTaskGroupLastAtomicTask(task, atomicTask)) {
                taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), "subTaskCompleted", true, 600L, true);
            }
        }

        return 1;
    }

    @Override

    public int handleFailure(Task task, AtomicTask atomicTask, String message) {
        log.info("error {}, ", message);
        Map<String, Object> param = getParameterMap(task, atomicTask);
        Long lpDataItemId = MapUtil.getLong(param, "dataItemId");
        if (task.getIsODR()) {
            String name = String.format("captureObj%s", lpDataItemId);
            String dataItemName = assetManagementService.i18nInApi(Dictionary.DATA_ITEM.getKeyPrefix() + lpDataItemId);
            message = String.format("Set %s fail: %s", dataItemName, message);
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), name, message, 600l, Boolean.FALSE);
            if (isSubTaskGroupLastAtomicTask(task, atomicTask)) {
                taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), "subTaskCompleted", true, 600L, true);
            }
        }
        return -1;
    }
}
